import { makeAutoObservable } from 'mobx'
import { MenuItem, ITabs, MenuOptions } from '@/interfaces/index'

class MenuStore {
  menuList: MenuItem[] = []
  menuData: MenuOptions[] = []
  tabList: Array<ITabs> = []

  constructor() {
    makeAutoObservable(this)
    this.resetTab()
  }

  setMenuList (menuList: MenuItem[]) {
    this.menuList = menuList
  }

  setMenuData (menuData: MenuOptions[]) {
    this.menuData = menuData
  }

  resetTab() {
    this.tabList = window.sessionStorage.getItem('tabList') 
    ? [...JSON.parse(window.sessionStorage.getItem('tabList')!)]
    : [{ label: '首页', path: '/home', key: '/home', closable: false }]
  }
  setTabList(list: Array<ITabs>) {
    this.tabList = list
  }

  addTabList(pathname: string) {
    const menu = this.getMenuByPath(pathname)
    this.tabList.push({
      label: menu?.title || pathname,
      path: pathname,
      key: pathname
    })
    window.sessionStorage.setItem('tabList', JSON.stringify(this.tabList))
  }

  getMenuByPath(path: string) {
    const dfs = (menu: MenuOptions[], path: string): MenuOptions | undefined => {
      for (const item of menu) {
        if (item.path === path) {
          return item
        }
        if (item.children) {
          const res = dfs(item.children, path)
          if (res) {
            return res
          }
        }
      }
    }
    return dfs(this.menuData, path)
  }

  removeTab(tabPath: string) {
    if (this.tabList.length === 1) return 
    this.tabList = this.tabList.filter(item => item.path !== tabPath)
    window.sessionStorage.setItem('tabList', JSON.stringify(this.tabList))
  }

  // 关闭其他，关闭所有
  closeMultipleTab(tabPath?: string) {
    this.tabList = this.tabList.filter(item => {
      return item.path === tabPath || item.path === '/home'
    })
    window.sessionStorage.setItem('tabList', JSON.stringify(this.tabList))
  }
}

export default new MenuStore()